package com.li.forum.controller;

import com.li.forum.common.AppResult;
import com.li.forum.common.ResultCode;
import com.li.forum.config.AppConfig;
import com.li.forum.model.User;
import com.li.forum.service.IUserService;
import com.li.forum.utils.MD5Utils;
import com.li.forum.utils.StringUtil;
import com.li.forum.utils.UUIDUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {
    
    @Resource
    private IUserService userService;
    
    /**
     * 注册接口
     * @param username 用户名
     * @param nickname 昵称
     * @param password 密码
     * @param passwordRequest 确认密码
     * @return
     */
    @PostMapping("/register")
    public AppResult register(@RequestParam("username") @NonNull String username,
                              @RequestParam("nickname") @NonNull String nickname,
                              @RequestParam("password") @NonNull String password,
                              @RequestParam("passwordRequest") @NonNull String passwordRequest){
        //校验；两次密码是否一致,不一致则返回错误信息
        if(!password.equals(passwordRequest)){
            log.info(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
        }
        
        //准备数据
        //生成一个盐值
        String salt = UUIDUtil.UUID_32();
        System.out.println(salt);
        //密码与盐值惊醒加密，得到密文
        String encryptPaassword = MD5Utils.md5Salt(password, salt);
        User user = new User(username,nickname,encryptPaassword, salt);
        
        userService.createNormalUser(user);
        return AppResult.success();
    }
    
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request, @RequestParam("username") @NonNull String username,
                           @RequestParam("password") @NonNull String password){
        User user = userService.login(username,password);
        if(user == null){
            log.warn(ResultCode.FAILED_LOGIN.toString());
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        HttpSession session = request.getSession(true);
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果跑
        return AppResult.success();
    }
    
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request, @RequestParam(value = "id", required = false) Long id){
        User user;
        //如果ID为空，从session中获取当前用户信息
        if(id == null){
            HttpSession session = request.getSession(false);
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //ID不为空，则查询用户信息
            user = userService.selectById(id);
        }
        if(user == null ){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        return AppResult.success(user);
    }
    
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        HttpSession session = request.getSession(false);
        if(session != null){
            log.info("退出成功");
            session.invalidate();
        }
        return AppResult.success("退出成功");
    }
    
    //修改个人信息
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo (HttpServletRequest request,
                                 @RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                 @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark) {
        //  接收参数
        //  对参数做非空校验（全部都为空，则返回错误描述）
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }
        
        // 从session中获取用户Id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        
        //  封装对象
        User updateUser = new User();
        updateUser.setId(user.getId()); // 用户Id
        updateUser.setUsername(username); // 用户名
        updateUser.setNickname(nickname); // 昵称
        updateUser.setGender(gender); // 性别
        updateUser.setEmail(email); // 邮箱
        updateUser.setPhoneNum(phoneNum); // 电话
        updateUser.setRemark(remark); // 个人简介
        
        //  调用Service中的方法
        userService.modifyInfo(updateUser);
        //  查询最新的用户信息
        user = userService.selectById(user.getId());
        // 把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION, user);
        // 返回结果
        return AppResult.success(user);
    }
    
    
    //修改密码
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword (HttpServletRequest request,
                                    @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        // 校验新密码与确认密码是否相同
        if (!newPassword.equals(passwordRepeat)) {
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //  获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  调用Service
        userService.modifyPassword(user.getId(), newPassword, oldPassword);
        //  销毁session
        if (session != null) {
            session.invalidate();
        }
        return AppResult.success();
    }
}


















